using Godot;
using System;

public partial class OptionsMenu : CanvasLayer
{
	[Signal] 
	public delegate void BackPressedEventHandler();

	SoundButton windowButton;
	HSlider sfxSlider;
	HSlider musicSlider;
	SoundButton backButton;
	ScreenTransition screenTransition;


	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		screenTransition = GetNode<ScreenTransition>("/root/ScreenTransition");
		sfxSlider = GetNode<HSlider>("%SfxSlider");
		musicSlider = GetNode<HSlider>("%MusicSlider");
		windowButton = GetNode<SoundButton>("%WindowButton");
		backButton = GetNode<SoundButton>("%BackButton");
		windowButton.Pressed += OnWindowButtonPressed;
		sfxSlider.ValueChanged += (value)=>{this.OnAudioSliderChanged(value,"sfx");};
		musicSlider.ValueChanged += (value)=>{this.OnAudioSliderChanged(value,"music");};
		backButton.Pressed += OnBackPressed;

		this.UpdateDisplay();

		
	}

	public void UpdateDisplay(){
		windowButton.Text = "Windowed";
		if( DisplayServer.WindowGetMode() == DisplayServer.WindowMode.Fullscreen){
			windowButton.Text = "Fullscreen";
		}

		sfxSlider.Value = this.GetBusVolumePercent("sfx");
		musicSlider.Value = this.GetBusVolumePercent("music");
	}

	public float GetBusVolumePercent(String busName){
		int busIndex = AudioServer.GetBusIndex(busName);
		float volumeDb = AudioServer.GetBusVolumeDb(busIndex);
		return Mathf.DbToLinear(volumeDb);
	}

	public void SetBusVolumePercent(String busName,float percent){
		int busIndex = AudioServer.GetBusIndex(busName);
		float volumeDb = Mathf.LinearToDb(percent);
		AudioServer.SetBusVolumeDb(busIndex,volumeDb);
	}

	public void OnWindowButtonPressed(){
		DisplayServer.WindowMode mode = DisplayServer.WindowGetMode();
		if(mode != DisplayServer.WindowMode.Fullscreen){
			DisplayServer.WindowSetMode(DisplayServer.WindowMode.Fullscreen);
		}else{
			DisplayServer.WindowSetFlag(DisplayServer.WindowFlags.Borderless,false);
			DisplayServer.WindowSetMode(DisplayServer.WindowMode.Windowed);
		}
		this.UpdateDisplay();
	}

	public void OnAudioSliderChanged(double value,String busName){
		this.SetBusVolumePercent(busName,(float)value);
	}

	public async void OnBackPressed(){
		screenTransition.Transition();
		await ToSignal(screenTransition,nameof(screenTransition.TransitionedHalfway)); //等待信号结束
		this.EmitSignal(nameof(BackPressed));
	}

	
}
